<script setup>
import { ref, onMounted } from 'vue';
import { getUserAPI, updateUserAPI, updatePasswordAPI,sendCodeAPI,deleteUserAPI,uploadAvatarAPI } from '@/api/User.js'; // 根据实际路径调整
import { useUserStore } from "@/stores/user";
import {ElMessage, ElMessageBox} from 'element-plus';

const store = useUserStore();
const userId = store.UserId; // 从 store 中获取用户 ID
const userInfo = ref({
  username: '',
  phone: '',
  address: '',
  avatar: '',
  updateTime: '',
  email: '',
  nickname: ''
});
const editField = ref(null); // 当前正在编辑的字段
const editData = ref({
  userId: userId,
  username: '',
  phone: '',
  address: '',
  email: '',
  nickname: ''
});
const showPasswordModal = ref(false);
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmNewPassword: ''
});

const showDeleteAccountModal = ref(false);
const deleteForm = ref({
  password: '',
  email: '',
  captcha: ''
});
const countdown = ref(0);
let countdownTimer = null;

const showAvatarUploadModal = ref(false);
const selectedFile = ref(null);
const previewImage = ref(null); // 用于存储图片预览 URL

// 打开上传头像对话框
const openAvatarUploadModal = () => {
  showAvatarUploadModal.value = true;
};

// 选择文件并显示预览
const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    selectedFile.value = file;
    previewImage.value = URL.createObjectURL(file); // 创建预览 URL
  }
};

// 确认上传头像
const uploadAvatar = async () => {
  if (!selectedFile.value) {
    ElMessage.error('请选择要上传的头像文件');
    return;
  }

  const formData = new FormData();
  formData.append('image', selectedFile.value);
  formData.append('userId', userId); // 从 store 中获取用户 ID

  try {
    const response = await uploadAvatarAPI(formData);
    if (response.data.code === 200) {
      ElMessage.success('头像上传成功');
      userInfo.value.avatar = response.data.data; // 更新页面上的头像
      store.avatar = response.data.data; // 更新 store 中的头像
      showAvatarUploadModal.value = false;
      selectedFile.value = null; // 重置选择的文件
      previewImage.value = null; // 清空预览 URL
    } else {
      ElMessage.error('头像上传失败');
    }
  } catch (error) {
    ElMessage.error('上传操作失败');
  }
};

// 取消上传
const cancelAvatarUpload = () => {
  showAvatarUploadModal.value = false;
  selectedFile.value = null;
  previewImage.value = null; // 清空预览 URL
};


const deleteRules = {
  required: true,
  pattern: /^[\x20-\x7E]{1,16}$/, // Modify as needed
  message: '输入不能为空，且必须为1-16个ASCII字符'
};
const openDeleteAccountModal = () => {
  showDeleteAccountModal.value = true;
};

const sendVerificationCode = async () => {
  if (deleteForm.value.email === '' ) {
    ElMessage.error('请输入有效的邮箱');
    return;
  }

  // Start countdown immediately
  if (countdown.value === 0) { // Ensure countdown isn't already active
    countdown.value = 120;
    countdownTimer = setInterval(() => {
      if (countdown.value > 0) {
        countdown.value--;
      } else {
        clearInterval(countdownTimer);
      }
    }, 1000);
  }

  try {
    const response = await sendCodeAPI(userId, deleteForm.value.email);

    if (response.data.code === 200) {
      ElMessage.success('验证码已发送');
    } else {
      ElMessage.error(response.data.msg);
      clearInterval(countdownTimer); // Stop countdown if sending failed
      countdown.value = 0;
    }

  } catch (error) {
    ElMessage.error('发送验证码失败');
    clearInterval(countdownTimer); // Stop countdown if there's an error
    countdown.value = 0;
  }
};


const confirmDeleteAccount = () => {
  const { password, email, captcha } = deleteForm.value;

  // 验证输入
  if (!deleteRules.pattern.test(password) || !deleteRules.pattern.test(email) || !deleteRules.pattern.test(captcha)) {
    ElMessage.error(deleteRules.message);
    return;
  }

  // 使用 ElMessageBox 进行确认
  ElMessageBox.confirm(
      '确定要注销账号吗？此操作不可恢复，请谨慎操作！',
      '确认注销',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  )
      .then(async () => {
        // 用户确认后执行注销操作
        try {
          const response = await deleteUserAPI({ userId, password, email, captcha });
          if (response.data.code === 200) {
            ElMessage.success('账号注销成功');
            showDeleteAccountModal.value = false;
            store.logout(); // 成功注销后执行登出操作
          } else {
            ElMessage.error('账号注销失败');
          }
        } catch (error) {
          ElMessage.error('注销操作失败');
        }
      })
      .catch(() => {
        // 用户取消，不执行任何操作
        ElMessage.info('已取消账号注销');
      });
};

const cancelDeleteModal = () => {
  showDeleteAccountModal.value = false;
  deleteForm.value = { password: '', email: '', captcha: '' };
  countdown.value = 0;
  clearInterval(countdownTimer);
};


// 验证规则
const passwordRules = {
  required: true,
  pattern: /^[\x20-\x7E]{1,16}$/,
  message: '密码不能为空，且必须为1-16个ASCII字符'
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserAPI(userId);
    userInfo.value = response.data.data;
    editData.value = {
      userId: userId,
      username: userInfo.value.username,
      phone: userInfo.value.phone,
      address: userInfo.value.address,
      email: userInfo.value.email,
      nickname: userInfo.value.nickname
    };
  } catch (error) {
    ElMessage.error('获取用户信息失败');
  }
};

// 保存某个字段的修改
const saveEdit = async (field) => {
  try {
    await updateUserAPI(editData.value);
    ElMessage.success(`${field} 修改成功`);
    await fetchUserInfo(); // 重新获取用户信息
    store.UserName = userInfo.value.username;
    store.nickname = userInfo.value.nickname;
    store.avatar = userInfo.value.avatar;
    editField.value = null;
  } catch (error) {
    ElMessage.error('信息修改失败');
  }
};

// 取消编辑
const cancelEdit = () => {
  editData.value = {
    userId: userId,
    username: userInfo.value.username,
    phone: userInfo.value.phone,
    address: userInfo.value.address,
    email: userInfo.value.email,
    nickname: userInfo.value.nickname
  };
  editField.value = null;
};

// 显示修改密码弹窗
const openPasswordModal = () => {
  showPasswordModal.value = true;
};

// 确认修改密码
const updatePassword = async () => {
  const { oldPassword, newPassword, confirmNewPassword } = passwordForm.value;

  // 验证输入
  if (!passwordRules.pattern.test(oldPassword) || !passwordRules.pattern.test(newPassword) || !passwordRules.pattern.test(confirmNewPassword)) {
    ElMessage.error(passwordRules.message);
    return;
  }

  if (newPassword !== confirmNewPassword) {
    ElMessage.error('新密码和确认密码不一致');
    return;
  }

  try {
    const response = await updatePasswordAPI(oldPassword, newPassword, userId);
    if (response.data.code === 400) {
      ElMessage.error('旧密码错误');
    } else if (response.data.code === 200) {
      ElMessage.success('密码修改成功');
      showPasswordModal.value = false;
      passwordForm.value = { oldPassword: '', newPassword: '', confirmNewPassword: '' };
    }
  } catch (error) {
    ElMessage.error('密码修改失败');
  }
};
//取消按钮，关闭弹窗和重置
const cancelPasswordModal = () => {
  showPasswordModal.value = false;
  passwordForm.value = { oldPassword: '', newPassword: '', confirmNewPassword: '' };
};
//退出登录
const logout = () => {
  //确认是否退出，ELbox
  ElMessageBox.confirm('确认退出？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 确认退出，执行退出逻辑
    store.logout();

  }).catch(() => {
    // 取消退出，不做任何操作
  });

};

onMounted(() => {
  fetchUserInfo();
});
</script>

<template>
  <div class="account-settings">

    <el-form label-width="120px" class="info-form" >
      <div class="user-avatar" @click="openAvatarUploadModal">
        <img v-if="userInfo.avatar" :src="userInfo.avatar" alt="用户头像"/>
        <img v-else src="@/assets/Photo/头像.png" alt="用户头像"/>
      </div>
      <el-form-item label="用户名" style="margin-left: 12%;">
        <template v-if="editField === 'username'">
          <el-input  style="width: 200px;" v-model="editData.username"/>
          <a @click="saveEdit('用户名')">保存</a> | <a @click="cancelEdit">取消</a>
        </template>
        <template v-else>
          {{ userInfo.username }}
          <a @click="editField = 'username'" style="margin-left: 50%">修改</a>
        </template>
      </el-form-item>
      <el-form-item label="昵&nbsp&nbsp&nbsp&nbsp称" style="margin-left: 12%;">
        <template v-if="editField === 'nickname'">
          <el-input style="width: 200px;" v-model="editData.nickname"/>
          <a @click="saveEdit('昵称')">保存</a> | <a @click="cancelEdit">取消</a>
        </template>
        <template v-else>
          {{ userInfo.nickname }}
          <a @click="editField = 'nickname'"  style="margin-left: 49.4%">修改</a>
        </template>
      </el-form-item>
      <el-form-item label="手机号" style="margin-left: 11.5%;">
        <template v-if="editField === 'phone'">
          <el-input style="width: 200px;" v-model="editData.phone"/>
          <a @click="saveEdit('手机号')">保存</a> | <a @click="cancelEdit">取消</a>
        </template>
        <template v-else>
          {{ userInfo.phone }}
          <a @click="editField = 'phone'" style="margin-left: 43%">修改</a>
        </template>
      </el-form-item>
      <el-form-item label="地&nbsp&nbsp&nbsp&nbsp址" style="margin-left: 12%;">
        <template v-if="editField === 'address'">
          <el-input v-model="editData.address"/>
          <a @click="saveEdit('地址')">保存</a> | <a @click="cancelEdit">取消</a>
        </template>
        <template v-else>
          {{ userInfo.address }}
          <a @click="editField = 'address'" style="margin-left:23.5%">修改</a>
        </template>
      </el-form-item>
      <el-form-item label="邮&nbsp&nbsp&nbsp&nbsp箱" style="margin-left: 12%;">
        <template v-if="editField === 'email'">
          <el-input style="width: 200px;" v-model="editData.email"/>
          <a @click="saveEdit('邮箱')">保存</a> | <a @click="cancelEdit">取消</a>
        </template>
        <template v-else>
          {{ userInfo.email }}
          <a @click="editField = 'email'" style="margin-left: 31.5%">修改</a>
        </template>
      </el-form-item>
      <el-form-item label="更新时间" style="margin-left: 13%" >
        <span>{{ new Date(userInfo.updateTime).toLocaleString() }}</span>
      </el-form-item>
      <el-form-item style="margin-left: 15%">
        <el-button type="warning" @click="openPasswordModal"  plain>修改密码</el-button>
        <el-button type="danger" @click="openDeleteAccountModal" plain>注销账号</el-button>
        <el-button type="primary" @click="logout" plain>退出登录</el-button>
      </el-form-item>
    </el-form>

    <el-dialog v-model="showPasswordModal" title="修改密码">
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="旧密码" :rules="[passwordRules]">
          <el-input type="password" v-model="passwordForm.oldPassword" show-password />
        </el-form-item>
        <el-form-item label="新密码" :rules="[passwordRules]">
          <el-input type="password" v-model="passwordForm.newPassword" show-password />
        </el-form-item>
        <el-form-item label="确认新密码" :rules="[passwordRules]">
          <el-input type="password" v-model="passwordForm.confirmNewPassword" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelPasswordModal">取消</el-button>
        <el-button type="primary" @click="updatePassword">确认修改</el-button>
      </template>
    </el-dialog>
  </div>

  <el-dialog v-model="showDeleteAccountModal" title="注销账号">
    <el-form :model="deleteForm" label-width="100px">
      <el-form-item label="密码" :rules="[deleteRules]">
        <el-input type="password" v-model="deleteForm.password" show-password />
      </el-form-item>
      <el-form-item label="邮箱" :rules="[deleteRules]">
        <el-input v-model="deleteForm.email" />
        <el-button @click="sendVerificationCode" :disabled="countdown > 0">
          {{ countdown > 0 ? `${countdown}s 后重新发送` : '发送验证码' }}
        </el-button>
      </el-form-item>
      <el-form-item label="验证码" :rules="[deleteRules]">
        <el-input v-model="deleteForm.captcha" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="cancelDeleteModal">取消</el-button>
      <el-button type="primary" @click="confirmDeleteAccount">确认注销</el-button>
    </template>
  </el-dialog>
  <el-dialog v-model="showAvatarUploadModal" title="上传头像">
    <div class="avatar-upload">
      <input type="file" @change="handleFileChange" accept="image/*" />
      <img v-if="previewImage" :src="previewImage" alt="图片预览" class="preview-image" />
    </div>
    <template #footer>
      <el-button @click="cancelAvatarUpload">取消</el-button>
      <el-button type="primary" @click="uploadAvatar">确认上传</el-button>
    </template>
  </el-dialog>

</template>

<style scoped>
.account-settings {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
}

h2 {
  text-align: left;
  margin-bottom: 20px;
  font-weight: bold;
}

.user-avatar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
  margin-left: 45%;
}

.user-avatar img {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}

.info-form {
  background-color: #f7f9fc;
  padding: 15px;
  border-radius: 8px;
  width: 850px;
  margin-left: -20%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.15);
}

.el-form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.el-form-item a {
  color: #409eff;
  cursor: pointer;
  margin-left: 10px;
}
.avatar-upload {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.preview-image {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 1px solid #ccc;
}

</style>
